#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>

int fd;

void handler(int sig, siginfo_t *info, void *ctx)
{
    char buf[50];
    int len = snprintf(buf, 50, "[SIGNAL] Received %s (Code: %d)\n",
                       (sig == SIGRTMIN) ? "SIGRTMIN" : "SIGINT", sig);
    write(fd, buf, len);
}

int main()
{
    fd = open("sigact.log", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    write(fd, "=== Reliable Signal Test ===\n", 30);

    struct sigaction act;
    act.sa_sigaction = handler;
    act.sa_flags = SA_SIGINFO; // 启用附加信息
    sigemptyset(&act.sa_mask);

    sigaction(SIGINT, &act, NULL);
    sigaction(SIGRTMIN, &act, NULL);

    sigset_t mask;
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGRTMIN);
    sigprocmask(SIG_BLOCK, &mask, NULL); // 阻塞信号

    sleep(5);                              // 模拟阻塞期间发送信号
    sigprocmask(SIG_UNBLOCK, &mask, NULL); // 解除阻塞
    sleep(10);                             // 添加此行，等待信号处理
    close(fd);
    return 0;
}